﻿using Darius.API.Application.Commands;
using IMES.Common.Dtos;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Darius.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    //添加特性
    [Authorize]
    public class UsersController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly IConfiguration configuration;

        public UsersController(IMediator mediator, IConfiguration configuration)
        {
            _mediator = mediator;
            this.configuration = configuration;
        }
        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString()
        {
            //读取配置文件
            var jwtSettings = configuration.GetSection("JWT").Get<JwtSettings>();
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(jwtSettings.SecurityKey);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名 hs256 加密算法
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            //Claims是指用户的身份信息，例如用户名、角色、权限等，它们通常被包含在一个ClaimsPrincipal对象中。
            var claims = new[]
            {
                  new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                  new Claim("Email","pmandy@163.com"),
                  new Claim("Phone","123456"),
                  new Claim("UserId","1"),
           };

            // 生成Token
            var token = new JwtSecurityToken(
                issuer: jwtSettings.Issuer,//发行者
                audience: jwtSettings.Audience,//受众
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials,
                claims: claims
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }

        /// <summary>
        /// 用户角色添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("UsersRoleAdd")]
        public async Task<ResultT<UsersRoleDto>> Handle(UsersCreateCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 用户显示
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("UsersSelect")]
        public async Task<Result> Handle(UsersSelectCommand request)
        {
            return await _mediator.Send(request);
        }


        /// <summary>
        /// 权限更新
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("PermissionAdd")]
        public async Task<Result> Handle(PermissionsCreateCommand request)
        {
            return await _mediator.Send(request);
        }

        /// <summary>
        /// 角色显示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<Result> SearchRole()
        {
            return await _mediator.Send(new RoleSearchCommand());
        }
        /// <summary>
        /// 权限添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> PermissionAdd(PermissionsCreateCommand cmd)
        {
            return await _mediator.Send(cmd);
        }
        /// <summary>
        /// 权限显示
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Result> PermissionSearch()
        {
            return await _mediator.Send(new PermissionSearchCommand());
        }
        /// <summary>
        /// 角色权限添加
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultT<RoleCreateDto>> PermissionRoleAdd(RolePermissionCreateCommand cmd)
        {
            return await _mediator.Send(cmd);
        }
        /// <summary>
        /// 角色权限显示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<Result> PermissionRoleSearch()
        {
            return await _mediator.Send(new RolePermissionSearchCommand());
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Login(LoginCommand cmd)
        {
            var list=await _mediator.Send(cmd);
            var token=CreateTokenString();
            return Ok(new
            {
                list = list,
                token = token
            });
        }
    }
}
